////////////////////////////////////////////////
//                单元名 : unitClientUpdateMsgDefine
//                作者 : Hawk
//                单元描述 : 
//                日期 : 2023-09-15
////////////////////////////////////////////////

{$IFDEF FPC}
{$H+}
{$MODE DELPHI}
{$ENDIF}

unit unitClientUpdateMsgDefine;

interface

uses
//{$IFnDEF FPC}
  Windows,
//{$ELSE}
//{$ENDIF}
  Messages;

const
  WM_NOTIFYMESSAGE = WM_APP + $10;

  UPDATEPROGRESS_STARTUPDATE = 1;
  UPDATEPROGRESS_CONNSVR = 2;
  UPDATEPROGRESS_FETCHUPDATEINFO = 3;
  UPDATEPROGRESS_PROJECTNOTFOUND = 4;
  UPDATEPROGRESS_STARTDOWNLOADFILE = 5;
  UPDATEPROGRESS_REPLACELOCALFILE = 6;
  UPDATEPROGRESS_NEEDRESTART = 7;
  UPDATEPROGRESS_UPDATECOMPLETE = 8;
  UPDATEPROGRESS_ACCESSDENYED = 9;

function FindOtherExe: WideString;
procedure StartUpdate(PrjID: UnicodeString; CBWnd: HWND);
procedure ClearInstallPath;

implementation

uses
{$IFnDEF FPC}
  ShellApi,
{$ELSE}
{$ENDIF}
  SysUtils, unitMisc;

function FindOtherExe: WideString;
var
  thisexe: WideString;
  sr: TSearchRec;
begin
  thisexe := ExtractFileName(ModuleFileName);
  Result := '';
  if FindFirst(ModuleFilePath + '*.exe', faAnyFile, sr) = 0 then
  begin
    if sr.Name <> thisexe then
      Result := sr.Name
    else if FindNext(sr) = 0 then
      Result := sr.Name;
    FindClose(sr);
  end;
end;

procedure StartUpdate(PrjID: UnicodeString; CBWnd: HWND);
var
  { si: TSHELLEXECUTEINFOW;
    a: array [0 .. MAX_PATH] of WideChar;
  }
  s: UnicodeString;
  si: _STARTUPINFOW;
  pi: _PROCESS_INFORMATION;
  e: Longword;
begin
  { FillChar(si, SizeOf(si), 0);
    si.cbSize := SizeOf(si);
    si.HWND := CBWnd;
    si.lpVerb := 'open';
    s := ModuleFilePath + FindOtherExe;
    si.lpFile := PWideChar(s);
    sp := PrjID + ' ' + IntToStr(CBWnd);
    si.lpParameters := PWideChar(sp);
    ShellExecuteEx(si); }
  FillChar(si, SizeOf(si), 0);
  si.cb := SizeOf(si);
  FillChar(pi, SizeOf(pi), 0);
  s := '"' + ModuleFilePath + FindOtherExe + '" P:' + PrjID + ' ' + IntToStr(CBWnd);
  DbgPrint('Call update : %s', [s]);
  if CreateProcessW(nil, PWideChar(s), NIL, NIL, False, CREATE_UNICODE_ENVIRONMENT, nil, nil, si, pi) then
    // CloseHandle(pi.hProcess)
  else
  begin
    e := GetLastError;
    DbgPrint('Start update process FAILED! %d(%s)', [e, SysErrorMessage(e)]);
  end;
end;

procedure ClearInstallPath;
var
  sr: TSearchRec;
  s: WideString;
begin
  s := ModuleFilePath;
  if FindFirst(s + '*.old', faAnyFile, sr) = 0 then
  begin
    DeleteFileW(PWideChar(s + sr.Name));
    while FindNext(sr) = 0 do
      DeleteFileW(PWideChar(s + sr.Name));
    FindClose(sr);
  end;
end;

end.
